package com.cci.kangdao.utilTool;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;


/**
 * @author 米艳春
 * @version 1.0
 * @Description: request参数的处理页
 * @Company: cumminschina
 * @date 2018-04-29
 */
public class ParameterTool {

    private static Logger log = Logger.getLogger(ParameterTool.class.getName());

    /**
     * get方式解析所有的参数.<br />
     *
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    public static Map<String, Object> getParameterRequest(HttpServletRequest request, boolean isEncoder)
            throws UnsupportedEncodingException {
        HashMap<String, Object> map = new HashMap<String, Object>();
        Map orimap = request.getParameterMap();
        Set keys = orimap.keySet();
        for (Object key1 : keys) {
            String key = (String) key1;
            String[] value = (String[]) orimap.get(key);
            if (value.length > 1) {
                String[] value2 = new String[value.length];
                for (int i = 0; i < value.length; i++) {
//					if (isEncoder) {
//						value2[i] = new String(value[i].getBytes("iso-8859-1"), "utf-8").trim();
//					} else {
//						value2[i] = new String(value[i]).trim();
//					}
                    value2[i] = new String(value[i]).trim();
                }
                map.put(key, value2);
            } else {
                map.put(key, value[0].trim());
            }
        }

//		/**
//		 * 拦截加密的项目id
//		 */
//		try {
//			if (map.get("id") != null && map.get("id").toString().length() >= 11) {
//				map.put("id", AESTool.decryptString(map.get("id").toString()));
//			}
//		} catch (Exception ex) {
//			log.error(ex.getMessage(), ex);
//		}
        writeRequestLog(map);
        return map;
    }

    private static void writeRequestLog(Map<String, Object> requestMap) {
        Map<String, Object> writeLog = new HashMap<>();
        if (MapUtils.isNotEmpty(requestMap)) {
            requestMap.forEach((k, v) -> {
                if (!"Authorization".equals(k)) {
                    writeLog.put(k, v);
                }
            });
        }
        log.info("请求参数：" + JsonUtils.toJsonString(writeLog));
    }


    public static Map<String, Object> getRequestBody(HttpServletRequest request) {
        Map<String, Object> requestMap = new HashMap<>();
        StringBuffer body = new StringBuffer();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                String str = null;
                while ((str = bufferedReader.readLine()) != null) {
                    body.append(str);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (StringUtils.isNotEmpty(body.toString())) {
            requestMap = JsonUtils.toJavaObject(body.toString(), Map.class);
        }
        writeRequestLog(requestMap);
        return requestMap;
    }

    public static String getRequestString(HttpServletRequest request) {
        StringBuffer body = new StringBuffer();
        BufferedReader bufferedReader = null;
        InputStream inputStream = null;
        try {
            inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
                String str = null;
                while ((str = bufferedReader.readLine()) != null) {
                    body.append(str);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.info("请求参数：" + body.toString());
        return body.toString();
    }

    /**
     * 判断是否为乱码
     *
     * @param str
     * @return
     */
    public static boolean isMessyCode(String str) {
        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            // 当从Unicode编码向某个字符集转换时，如果在该字符集中没有对应的编码，则得到0x3f（即问号字符?）
            // 从其他字符集向Unicode编码转换时，如果这个二进制数在该字符集中没有标识任何的字符，则得到的结果是0xfffd
            // System.out.println("--- " + (int) c);
            if ((int) c == 0xfffd) {
                // 存在乱码
                // System.out.println("存在乱码 " + (int) c);
                return true;
            }
        }
        return false;
    }

    /**
     * 给前端返回消息
     *
     * @param response
     */
    public static void writeResponse(HttpServletResponse response, String result) {
        try {
            /**
             * 返回前端消息
             */
            log.info("响应参数：" + result);
            response.setContentType("text/json;charset=UTF-8");
            response.getOutputStream().write(result.getBytes("utf-8"));
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }


    public static void writeResponse(HttpServletResponse response, Integer status, String message) {
        try {
            JSONObject obj = new JSONObject();
            obj.put("status", status);
            obj.put("msg", message);
            writeResponse(response, obj.toString());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    public static void writeResponse(HttpServletResponse response, Integer status, String message, Object object) {
        try {
            JSONObject obj = new JSONObject();
            obj.put("status", status);
            obj.put("msg", message);
            obj.put("data", object);
            writeResponse(response, obj.toString());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    public static void writeResponseForNull(HttpServletResponse response, Integer status, String message, Object object) {
        try {
            net.sf.json.JSONObject obj = new net.sf.json.JSONObject();
            obj.put("status", status);
            obj.put("msg", message);
            obj.put("data", object);
            writeResponse(response, obj.toString());
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    public static void writeSuccessResponse(HttpServletResponse response) {
        try {
            writeSuccessResponse(response, null);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    public static void writeSuccessResponse(HttpServletResponse response, Object object) {
        try {
            Map<String, Object> obj = new LinkedHashMap<>(3);
            obj.put("status", 0);
            obj.put("msg", "success");
            if (null != object) {
                obj.put("data", object);
            }
            writeResponse(response, JsonUtils.toJsonString(obj));
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    /**
     * 给前端返回消息
     *
     * @param response
     */
    public static void writeErrorResponse(HttpServletResponse response) {
        try {
            /**
             * 返回前端消息
             */
            String result = "{\"status\": -99,\"msg\": \"未知错误\",\"data\":{}}";
            log.info("响应参数：" + result);
            response.setContentType("text/json;charset=UTF-8");
            response.getOutputStream().write(result.getBytes("utf-8"));
            response.getOutputStream().flush();
            response.getOutputStream().close();
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    public static void writeErrorResponse(HttpServletResponse response, Integer error, Object data) {
        try {
            /**
             * 返回前端消息
             */
            JSONObject obj = new JSONObject();
            obj.put("status", error);
            obj.put("msg", ApiErrorCode.getInstance().getErrorMsg(error));
            if (null != data) {
                obj.put("msg", data);
            }
            writeResponse(response, obj.toString());
            obj = null;
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    }

    public static void writeErrorResponse(HttpServletResponse response, Integer error) {
        writeErrorResponse(response, error, null);
    }

}
